import { configAppStore } from '@/store/config'
import { awaitTo } from '@/utils'
import { ref } from 'vue'

/**
 * 消息订阅 Hook
 * 用于内部和外部之间的双向通信
 */
export function useMessageSubscribe<T>() {
  const isRunning = ref(false)
  const listeners = ref<Array<(data: T | null) => void>>([])
  const stopListeners = ref<Array<() => void>>([])
  const requestApi = ref<(params) => Promise<IResData<T>> | null>(null)
  const timer = ref<ReturnType<typeof setInterval> | null>(null)

  const { config } = configAppStore()
  /**
   * 开始订阅
   * @param options 配置选项
   */
  async function start(
    api: () => Promise<IResData<T>>,
    options?: { onMessage?: (data: T) => void; onStop?: () => void },
  ) {
    if (isRunning.value) {
      return
    }

    isRunning.value = true
    requestApi.value = api

    timer.value = setInterval(async () => {
      checkApi()
    }, config.refresh_interval * 1000)

    // 注册消息监听器
    if (options?.onMessage) {
      listeners.value.push(options.onMessage)
    }

    // 注册停止监听器
    if (options?.onStop) {
      stopListeners.value.push(options.onStop)
    }

    return {
      stop,
      sendMessage,
    }
  }

  /** 额外参数 */
  const extraParams = ref<{ [key: string]: any }>({})

  /**
   * 设置额外参数
   * @param params 额外参数
   */

  function setExtraParams(params: { [key: string]: any }) {
    extraParams.value = { ...extraParams.value, ...params }
  }

  /**
   * 请求 API
   * @returns
   */
  async function checkApi() {
    const { result } = await awaitTo(requestApi.value({ ...extraParams.value }))
    if (result) {
      sendMessage(result.data)
    }
  }

  /**
   * 发送消息
   * @param data 消息数据
   */
  function sendMessage(data: T | null) {
    if (!isRunning.value) {
      return
    }

    // 通知所有消息监听器
    listeners.value.forEach((listener) => {
      try {
        if (data !== null) {
          listener(data)
        }
      } catch (error) {
        console.error('消息处理错误：', error)
      }
    })
  }

  /**
   * 停止订阅
   */
  function stop() {
    if (!isRunning.value) {
      return
    }

    isRunning.value = false

    // 通知所有停止监听器
    stopListeners.value.forEach((listener) => {
      try {
        listener()
      } catch (error) {
        console.error('停止处理错误：', error)
      }
    })

    // 清空所有监听器
    listeners.value = []
    stopListeners.value = []
    requestApi.value = null
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
    }
  }

  return {
    isRunning,
    start,
    stop,
    sendMessage,
    setExtraParams,
  }
}

export default useMessageSubscribe
